package com.amarsoft.apot.service.impl;

import com.amarsoft.apot.service.SendEmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
public class SendEmailServiceImpl implements SendEmailService {

    @Autowired
    private JavaMailSenderImpl mailSender;

    /**
     * 单个邮件发送
     * @param sendFrom 发件人
     * @param sendTo 收件人
     * @param subject 主题
     * @param content 内容
     * @param attachment 附件
     */
    @Override
    public void send(String sendFrom, String sendTo, String subject, String content, String attachment) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper mimeMessageHelper = null;
        try {
            mimeMessageHelper = new MimeMessageHelper(mimeMessage,true);
            // 主题和内容
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(content,true);
            // 发送邮件附件
            if(!StringUtils.isEmpty(attachment)) {
                String attachmentName = attachment.trim().substring(attachment.lastIndexOf("/") + 1);
                mimeMessageHelper.addAttachment(attachmentName,new File(attachment));
            }
            // 发件人和收件人
            mimeMessageHelper.setFrom(sendFrom);
            mimeMessageHelper.setTo(sendTo);

            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }



}
